<?php
/** 观察者接口 */
interface Observer
{
    public function update();
}
/** 主题 */
class Subject
{
    /** @var Observer[] $list */
    public $list=[];
    /** @param Observer $observer */
    public function attach($observer)
    {
        $this->list[] = $observer;
    }
    /** @param Observer $observer */
    public function detach($observer)
    {
        $index = array_search($observer, $this->list);
        unset($this->list[$index]);
    }
    public function notify()
    {
        foreach($this->list as $observer){
            $observer->update();
        }
    }
    protected $data="";
    public function setData($data)
    {
        $this->data=$data;
        $this->notify();   
    }
    public function getData()
    {
        return $this->data;
    }
}

class ObserverA implements Observer
{
    /** @var Subject $subject */
    protected $subject = null;
    /** @param Subject $subject */
    public function __construct($subject)
    {
        $subject->attach($this);
        $this->subject=$subject;
    }
    public function update()
    {
        echo "ObserverA:" . $this->subject->getData();
    }
}

$subject = new Subject;
$observer = new ObserverA($subject);
$subject->setData("2333");

